package com.orion.smart.controller;

import com.orion.smart.po.User;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;

/**
 * hello
 *
 * @author <a href="http://github.com/athc">dujf</a>
 * @date 2018/8/31
 * @since JDK1.8
 */
@RestController
@RequestMapping("/hello")
public class HelloController {

  /**
   * 创建
   *
   * @param user
   * @return
   */
  @PostMapping
  public User create(User user) {
    return user;
  }

  /**
   * 查询
   *
   * @param name
   * @return
   */
  @GetMapping
  public User getName(String name) {
    return new User();
  }

  /**
   * 修改
   *
   * @param name
   * @return
   */
  @PutMapping
  public String update(String name) {
    return name;
  }

  /**
   * 删除
   *
   * @param name
   * @return
   */
  @DeleteMapping
  public String delete(String name) {
    return name;
  }

  /**
   * hello world graphql
   *
   * @param args
   */
  public static void main(String[] args) {
    String schema = "type Query{hello: String}";

    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

    RuntimeWiring runtimeWiring = newRuntimeWiring()
        .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
        .build();

    SchemaGenerator schemaGenerator = new SchemaGenerator();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

    GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
    ExecutionResult executionResult = build.execute("{hello}");

    System.out.println(executionResult.getData().toString());
  }
}
